import React, { useState ,useEffect} from 'react'
import { Modal, ModalHeader, ModalBody, ModalFooter, Button } from 'reactstrap'
import { Spinner } from 'reactstrap';
import ClassList from './user/ClassList'

const Add = props => {
    const [imglist, setImglist] = useState([]);
    const [content, setContent] = useState('');
    const [uping, setUping] = useState(false);
    const [classList, setClassList] = useState([]);
    const [show, setShow] = useState(false);
    const [classify, setClassify] = useState({});
    const [name, setName] = useState('');
    const [add, setAdd] = useState(false);

    useEffect(() => {
        let load = async ()=>{
            let resp = await fetch('/api/index/getClass');
            if(resp.ok){
                let json = await resp.json();
                setClassList(json);
            }
        }
        load();
        return () => {
        };
    }, [])

    let close = (index) => {
        let newlist = imglist.slice();
        let url = newlist.splice(index, 1);
        window.URL.revokeObjectURL(url[0].url);
        setImglist(newlist);
    }
    let upLoadImg = (e) => {
        if (e.target.files.length == 0) {
            return;
        }
        let img = window.URL.createObjectURL(e.target.files[0]);
        setImglist([...imglist, { url: img, data: e.target.files[0] }]);
    }
    let closeWindow = (e) => {
        imglist.forEach((item) => {
            window.URL.revokeObjectURL(item.url);
        });
        setContent('');
        setImglist([]);
        props.toggle(e);
    }
    let UpLoad = async () => {
        if (imglist.length == 0) {
            alert("请选择相片");
            return;
        }
        if(JSON.stringify(classify)=='{}'){
            alert('请选择相册');
            return ;
        }
        let data = new FormData();
        for (let index = 0; index < imglist.length; index++) {
            const element = imglist[index];
            data.append(`file[]`, element.data);
        }
        data.append('classname',classify.name);
        data.append('classid',classify.id);
        data.append('content', content);
        let resp = await fetch('/api/index/upload', {
            method: 'POST',
            body: data
        });
        if (resp.ok) {
            imglist.forEach((item) => {
                window.URL.revokeObjectURL(item.url);
            });
            setContent('');
            setImglist([]);
            props.toggle();
        } else {
            alert('发布失败请重试');
        }
    }
    let newBum = async () => {
        if(name==''){
            alert("请输入相册名称");
            return;
        }
        setAdd(true);
        let data = new FormData();
        data.append('name',name);
        let resp = await fetch('/api/index/addClass',{
            method:'POST',
            body:data
        })
        if(resp.ok){
            setAdd(false);
            setClassList([...classList,await resp.json()]);

        }else{
            alert("相册创建失败："+await resp.text());
            setAdd(false);
        }
    }
    let setClass = (c) => {
        setClassify(c);
        setShow(false);
    }
    return (
        <Modal isOpen={props.modal} backdrop='static' toggle={props.toggle}>
            <ModalHeader style={{ width: '100%' }}>上传图片
            </ModalHeader>
            <ModalBody>
                <div>
                    <div className='up-list'>
                        {imglist.map((img, i) => {
                            return <UpItem close={close} img={img.url} index={i} key={i} />
                        })}
                        <label htmlFor='upInput' className='selectimg'></label>
                    </div>
                    <input type='file' id='upInput' onChange={upLoadImg} accept='image/*' style={{ width: 0, height: 0 }}></input>
                </div>
                <div style={{ position: 'relative' }}>

                    <div className='div-select'>
                        <div className='class-select'>
                            <label style={{color:'#aaa'}}>添加至相册：</label>
                            <i className='icon-select'><svg style={{ marginLeft: 3 }} t="1570846328066" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2466" width="20" height="20"><path d="M467.231 780.553 19.669 332.991c-24.753-24.752-24.753-64.788 0-89.541 24.681-24.682 64.788-24.753 89.541 0l402.792 402.791L914.793 243.45c24.682-24.682 64.788-24.753 89.541 0 24.753 24.752 24.681 64.788 0 89.541L556.771 780.553C532.02 805.234 491.984 805.234 467.231 780.553z" p-id="2467" fill="#ffffff"></path></svg></i>
                            <a href='javascript:;' className='shw' onClick={e => { setShow(!show) }}>{classify.name}</a>
                        </div>
                    </div>
                    <div className='add-context'>
                        <label>为图片添加合适的描述</label>
                        <textarea name='content' className='txa' id='add-txa' value={content} onChange={(e) => { setContent(e.target.value) }}></textarea>

                    </div>
                    {show ?
                        <div className='wrap'>
                            <ClassList setClass={setClass} list={classList} select={classify}/>
                            <div className='clr'>
                                <input value={name} onChange={e => { setName(e.target.value) }}></input>
                                {add ? <Spinner /> :
                                    <a className='newxc' href='javascript:;' onClick={newBum}><span style={{ color: '#FFFFFF' }}>新建相册</span></a>
                                }
                            </div>
                        </div> : ''}
                </div>
            </ModalBody>
            <ModalFooter style={{ textAlign: 'center' }}>
                <Button color="primary" onClick={UpLoad}>{uping ? <Spinner /> : '发布'}</Button>{' '}
                <Button color="secondary" onClick={closeWindow}>取消</Button>
            </ModalFooter>
        </Modal>
    )
}
const UpItem = props => {
    return (<div className='up-item'>
        <div className='up-del'>
            <a onClick={e => { props.close(props.index) }} style={{ float: "right", marginRight: 10 }}>
                <svg t="1569739386033" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2470" width="16" height="16"><path d="M934.184927 199.723787 622.457206 511.452531l311.727721 311.703161c14.334473 14.229073 23.069415 33.951253 23.069415 55.743582 0 43.430138-35.178197 78.660524-78.735226 78.660524-21.664416 0-41.361013-8.865925-55.642275-23.069415L511.149121 622.838388 199.420377 934.490384c-14.204513 14.20349-33.901111 23.069415-55.642275 23.069415-43.482327 0-78.737272-35.230386-78.737272-78.660524 0-21.792329 8.864902-41.513486 23.094998-55.743582l311.677579-311.703161L88.135828 199.723787c-14.230096-14.255679-23.094998-33.92567-23.094998-55.642275 0-43.430138 35.254945-78.762855 78.737272-78.762855 21.741163 0 41.437761 8.813736 55.642275 23.069415l311.727721 311.727721L822.876842 88.389096c14.281261-14.255679 33.977859-23.069415 55.642275-23.069415 43.557028 0 78.735226 35.332716 78.735226 78.762855C957.254342 165.798117 948.5194 185.468109 934.184927 199.723787" p-id="2471" fill="#eeeeee"></path></svg>
            </a>
        </div>
        <img src={props.img} className='up-img'></img>
    </div>);
}

export default Add
